package org.example.server8001.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.example.SystemDemo.utils.StringUtil;
import org.example.SystemDemo.comment.enity.HostInfo;
import org.example.server8001.service.InfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Objects;

/**
 * 心跳检测
 */
@RestController
@RequestMapping("/api/v1/ref")
public class RefController {

    public static ArrayList<Long> ids = new ArrayList<>();

    @Autowired
    InfoService infoService;

    /**
     * 刷新存活状态
     * @param req 请求信息
     * @param index 服务器id
     * @return 返回是否刷新成功
     */

    @RequestMapping(value = "/refurbish",method = RequestMethod.GET)
    public boolean Refurbish(HttpServletRequest req, @RequestParam("index") long index){
        // 判断index非空
        if (index == 0) return false;

        final String addr = StringUtil.getIpAddr(req);
        final HostInfo one = infoService.getOne(Wrappers.<HostInfo>lambdaQuery().eq(HostInfo::getId, index));
        if(!Objects.isNull(one)){
            // 如果ip地址不相同刷新连接ip
            if (!addr.equals(one.getHostIp())){
                one.setHostIp(addr);
                this.infoService.updateById(one);
            }
            // 刷新服务器状态
            if (!one.isConnectStatus()){
                one.setConnectStatus(true);
                this.infoService.updateById(one);
            }
            if (!RefController.ids.contains(index)) {
                RefController.ids.add(index);
            }
            return true;
        }
        return false;
    }
}
